<?php
namespace My\Controller;

use Utuo\BackgroundController;
use Utuo\Wechat\UtuoWechatExt;
use My\Model\TemplateMessageModel;

class WechatController extends BackgroundController
{
    // 初始化
    public function _initialize()
    {
        $this->setControllerTitle('微信公众平台设置');
        $this->setActionTitle('index', '微信公众平台设置');
    }
    
    // 微信公众平台设置
    public function indexAction()
    {
        $d = D('Wechat');
        $wechat = $d->where("cid=%d", $this->aid)->find();
        if (! $wechat) {
            if ($d->data(array(
                'cid' => $this->aid,
                'token' => $this->getApiToken()
            ))->add()) {
                $wechat = $d->where("cid=%d", $this->aid)->find();
            } else {
                $this->error("添加数据失败");
            }
        }
        $wechat['url'] = $this->getApiUrl();
        $types = array();
        foreach ( TemplateMessageModel::$TEMPLATE_TYPE as $k => $v ) {
        	$types[$k] = $v['title'];
        }
        /* tmp+ 2015-6-23 S*/
        $wechat['payUrl'] =  sprintf('http://%s%s/%s', $_SERVER['HTTP_HOST'], $_SERVER['SCRIPT_NAME'], "Home/DisShopPay/" ); //uu($this->aid, 'Home', 'DisShopPay', '', "", true); // 支付目录
        $wechat['jsSafeDomain'] = $_SERVER['HTTP_HOST']; // js安全域名
        $wechat['redirectDomain'] = $_SERVER['HTTP_HOST']; // 授权回调页面域名
        $wechat['bussinessDomain'] = $_SERVER['HTTP_HOST']; // 业务域名
        /* tmp+ 2015-6-23 E*/
        $this->assign("templateTypeOptions", $this->getOption($types, $wechat['templateType'], '===请选择==='));
        $this->assign('wechat', $wechat);
        $this->display();
    }
    
    // 一键绑定
    public function bindAction()
    {
        $account = I('account') or $this->ajaxError('账号不能为空');
        $password = I('password') or $this->ajaxError('密码不能为空');
        $url = I('url') or $this->ajaxError('接口地址不能为空');
        $token = I('token') or $this->ajaxError('接口token不能为空');
        $wechatExt = new UtuoWechatExt(array(
            'account' => $account,
            'password' => $password
        ));
        $result = $wechatExt->setInterface($url, $token);
        $result = json_decode($result, true);
        if ($result['base_resp']['ret'] == 0) {
            $this->ajaxSuccess('一键绑定公众平台成功'); 
        } else {
            $this->ajaxError('绑定失败，请重试。(' . $result['base_resp']['err_msg'] . ')');
        }
    }
    
    // 更新接口设置
    public function indexPostAction()
    {
        $d = D("Wechat");
        if ($d->create()) {
            if (false !== $d->save()) {
                $this->ajaxSuccess();
            } else {
                $this->ajaxError($d->getError());
            }
        } else {
            $this->ajaxError($d->getError());
        }
    }
    
    // 获取接口URL
    protected function getApiUrl()
    {
        $id = $this->aid;
        $baseUrl = sprintf('http://%s%s', $_SERVER['HTTP_HOST'], $_SERVER['SCRIPT_NAME']);
        $apiUrl = uu($id, 'Api', 'Wechat', 'index', "id={$id}", true);
        return $apiUrl;
    }
    
    // 获取接口TOKEN
    protected function getApiToken()
    {
        $token = $this->aid . rand(100000, 999999);
        $token = dechex($token);
        return $token;
    }
    
    // 更新TOKEN
    public function updateTokenPostAction()
    {
        $token = $this->getApiToken();
        if (D("Wechat")->where("cid={$this->aid}")->setField("token", $token)) {
            $this->ajaxSuccess('更新Token成功，请到微信公众平台后台重新绑定', array(
                'token' => $token
            ));
        } else {
            $this->ajaxError("更新token失败，请重试");
        }
    }
}